package com.applcn.message.utils.sms;

import com.applcn.core.base.Result;
import com.applcn.message.apollo.TencentSmsConfig;
import com.applcn.message.enums.SmsChoiceEnum;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * com.applcn.message.utils.sms
 * Description:
 *
 * @author: 大妖怪
 * @date: 2020-02-19 22:56
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class TencentSmsUtil implements AbstractSmsUtil {

    private final TencentSmsConfig tencentSmsConfig;

    @Override
    public int getCode() {
        return SmsChoiceEnum.TENCENT_SMS.getCode();
    }

    @Override
    public Result sendSmsMessage(String phone, String smsSign, String templateId, String... params) {
        SmsSingleSender sender = new SmsSingleSender(tencentSmsConfig.getAppId(), tencentSmsConfig.getAppKey());
        SmsSingleSenderResult result = null;
        try {
            result = sender.sendWithParam("86", phone, Integer.parseInt(templateId), params, smsSign, "", "");
        } catch (HTTPException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Objects.equals(result.result, "0")) {
            return Result.ok();
        } else {
            log.info("腾讯云短信验证码发送失败，错误码:{}, 错误信息:{}", result.result, result.errMsg);
            return Result.error();
        }
    }

    @Override
    public Result sendMessageGroup(String[] phones, String smsSign, String templateId, String[] params) {
        SmsMultiSender msender = new SmsMultiSender(tencentSmsConfig.getAppId(), tencentSmsConfig.getAppKey());
        SmsMultiSenderResult result = null;
        try {
            result = msender.sendWithParam("86", phones,
                    Integer.parseInt(templateId), params, smsSign, "", "");
        } catch (HTTPException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Objects.equals(result.result, "0")) {
            return Result.ok();
        } else {
            log.info("腾讯云短信验群发失败，错误码:{}, 错误信息:{}", result.result, result.errMsg);
            return Result.error();
        }
    }
}
